//
//  JYTPinPhoneViewController.m
//  JYT_IOS
//
//  Created by nxa-tankeke on 16/12/16.
//  Copyright © 2016年 nxa-yuanguoxiang. All rights reserved.
//

#import "JYTPinPhoneViewController.h"
#import "JYTRegisteredHandler.h"
#import "JYTSetPasswardViewController.h"
#import <SVProgressHUD.h>
#define SECOND 60

@interface JYTPinPhoneViewController ()
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet UITextField *textField;

@property (weak, nonatomic) IBOutlet UITextField *pinCodeField;
@property (weak, nonatomic) IBOutlet UIButton *checkBtn;


@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, assign) int initialTimer;
@end

@implementation JYTPinPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSDictionary *dic = @{@"lftBtnBgImg":@"ic_goback",
                          @"lftBtnTitle":@"no",
                          @"pageTitle":@"忘记密码",
                          @"rhtBtnBgImg":@"no",
                          @"rhtBtnTitle":@"no"};
    
    [self setNavgationBarWithDic:dic];
    
    self.nextBtn.layer.cornerRadius = 5.0;
    self.checkBtn.layer.cornerRadius = 5.0;
    self.nextBtn.layer.masksToBounds = YES;
    [self.checkBtn.titleLabel setTextAlignment: NSTextAlignmentLeft];
    [self.checkBtn setBackgroundColor:[UIColor colorWithRed:131/255.0f green:182/255.0f blue:248/255.0f alpha:1]];
    [self.nextBtn setBackgroundColor:[UIColor colorWithRed:131/255.0f green:182/255.0f blue:248/255.0f alpha:1]];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.checkBtn.enabled = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    MyLog(@"==销毁定时器==");
    
    //self.checkBtn.enabled = YES;
    [self.checkBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    //_initialTimer = SECOND;
}

- (IBAction)clickCheckBtn:(id)sender {
    
    NSString *phone =  self.textField.text;
    if (!phone || [phone isEqualToString:@" "] || [phone isEqualToString:@""])
    {
        [self showMessage:@"请输入用户名"];
        
        return;
    }
    
    _initialTimer = SECOND;
    [[JYTRegisteredHandler shared] getPinCodeWithPhone:phone withHandler:^(NSString *code) {
        
        self.checkBtn.userInteractionEnabled = NO;
        [self.checkBtn setTitle:[NSString stringWithFormat:@"%02d秒后重新获取",SECOND] forState:0];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerStart:) userInfo:nil repeats:YES];
        
        if ([code isEqualToString:@"1"]) {
            [self showMessage:@"短信验证码发送失败"];
        } else {
            
            [self showMessage:@"短信验证码发送成功"];
        }
        
    }];
}

- (IBAction)clicknextBtn:(id)sender {
    
    NSString *phone =  self.textField.text;
    if (!phone || [phone isEqualToString:@" "] || [phone isEqualToString:@""])
    {
        [self showMessage:@"请输入用户名"];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"正在加载......"];
    NSString *pinCode = self.pinCodeField.text;
    
    [[JYTRegisteredHandler shared] checkPinCodeWithPhone:phone pinCode:pinCode withHandler:^(NSString *message, NSString *code) {
        
        if ([code isEqualToString:@"0"]) {
            [SVProgressHUD dismiss];
            [self showMessage:@"验证成功"];
            [self.textField resignFirstResponder];
            [self.pinCodeField resignFirstResponder];
            JYTSetPasswardViewController *s = [[JYTSetPasswardViewController alloc] init];
            s.userName = phone;
            [self pushViewController:s];
            return ;
        }
        
        if ([code isEqualToString:@"2"]) {
            [SVProgressHUD dismiss];
            [self showMessage:message];
            return ;
        }
        
    }];

}

-(void)timerStart:(NSTimer *)theTimer {
    if (_initialTimer == 1){
        _initialTimer = 60;
        [self stop];
    }else{
        _initialTimer--;
        [self.checkBtn setTitle:[NSString stringWithFormat:@"%02d秒后重新获取",_initialTimer] forState:0];
        
    }
}


- (void)stop{
    self.checkBtn.userInteractionEnabled = YES;
    if (_timer) {
        [_timer invalidate]; //停止计时器
        [self.checkBtn setTitle:@"重新获取" forState:UIControlStateNormal];
    }
}

-(void)dealloc
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    MyLog(@"---------销毁定时器");
}
- (void)showMessage:(NSString *)message
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    label.text = message;
    
    //    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
    //初始化段落，设置段落风格
    
    NSMutableParagraphStyle *paragraphstyle=[[NSMutableParagraphStyle alloc]init];
    paragraphstyle.lineBreakMode=NSLineBreakByCharWrapping;
    
    //设置label的字体和段落风格
    
    NSDictionary *dic=@{NSFontAttributeName:label.font,NSParagraphStyleAttributeName:paragraphstyle.copy};
    
    //计算label的真正大小,其中宽度和高度是由段落字数的多少来确定的，返回实际label的大小
    
    CGRect rect=[label.text boundingRectWithSize:CGSizeMake(290, 9000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    CGSize LabelSize = CGSizeMake(rect.size.width, rect.size.height);
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    showview.frame = CGRectMake((CURRENT_SCREEN_WIDTH - LabelSize.width - 20)/2, CURRENT_SCREEN_HEIGHT - 100, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:2 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
